package com.thp.bigdata.webClick.mr.pre;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import com.thp.bigdata.webClick.mrBean.WeblogBean;
import com.thp.bigdata.webClick.mrBean.WeblogParser;

/**
 * 处理原始的日志，过滤出真实的PV情况
 * 1)转换时间格式
 * 2)对缺失的字段填充默认值
 * 3)对记录标记valid和invalid
 * @author 汤小萌
 *
 */
public class WeblogPreProcess {

	
	static class WeblogPreProcessMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
		
		Set<String> pages = new HashSet<String>();
		Text k = new Text();
		NullWritable v = NullWritable.get();
		/**
		 * 从外部加载网站url分类
		 */
		@Override
		protected void setup(Context context)
				throws IOException, InterruptedException {
			/*pages.add("/about/");
			pages.add("/black-ip-list/");
			pages.add("/cassandra-clustor/");
			pages.add("/finance-rhive-repurchase/");
			pages.add("/hadoop-family-roadmap/");
			pages.add("/hadoop-hive-intro/");
			pages.add("/hadoop-zookeeper-intro/");
			pages.add("/hadoop-mahout-roadmap/");*/
			
			Properties pop = new Properties();
			InputStream in = WeblogPreProcessMapper.class.getClassLoader().getResourceAsStream("url.propeties");
			pop.load(in);
			String urlStr = pop.getProperty("url");
			String[] urls = urlStr.split(",");
			for(String url : urls) {
				pages.add(url);
			}
			
		}
		
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			WeblogBean weblogBean = WeblogParser.parser(line);
			// 可插拔的方法  ： 过滤  js/图片/css等静态资源
			WeblogParser.filterStaticResource(weblogBean, pages);
			
			if(weblogBean.isValid()) {  // 无效的数据都被过滤出去了
				k.set(weblogBean.toString());
				context.write(k, v);
			}
			
		}
		
		
	}
	
	
	public static void main(String[] args) throws Exception {

		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);

		job.setJarByClass(WeblogPreProcess.class);

		job.setMapperClass(WeblogPreProcessMapper.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);

//		 FileInputFormat.setInputPaths(job, new Path(args[0]));
//		 FileOutputFormat.setOutputPath(job, new Path(args[1]));
		FileInputFormat.setInputPaths(job, new Path("f:/weblog/input"));
		FileOutputFormat.setOutputPath(job, new Path("f:/weblog/output"));

		job.setNumReduceTasks(0);
		
		job.waitForCompletion(true);

	}
	
	
	
	
}
